package com.hb.trade.api.routine.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.spire.doc.*;
import com.spire.doc.collections.CellCollection;
import com.spire.doc.collections.RowCollection;
import com.spire.doc.collections.TableCollection;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import fzzn.core.spire.HtmlWordConverter;
import org.fzzn.core.web.util.SpringUtils;

import java.awt.*;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * describe:
 * 继承 fzzn.core.spire.OfficeUtil 操作doc文件与html互换
 * @author zhongdl
 * @date 2022/04/21
 */
public class OfficeUtil extends fzzn.core.spire.OfficeUtil {

    /**
     * @param wordFile:word文件只能是(docx结尾)
     * @param params:占位符填充, 占位符必须使用${xxx}包裹, params中写成{"xxx":"value"}的形式, 不需要填充传null
     * @Description:word转word替换参数
     * @Author: zhongdl
     * @Date:2022/4/21 18:11
     * @return: {@link byte[] }
     **/
    public static byte[] wordToWordBytes(File wordFile, Map<String, String> params) {
        HtmlWordConverter converter = new HtmlWordConverter();
        converter.from(HtmlWordConverter.FileTypeEnum.DOCX)
                .to(HtmlWordConverter.FileTypeEnum.DOCX)
                .open("${")
                .close("}");
        if (CollUtil.isNotEmpty(params)) {
            converter.with(params);
        }
        return converter.getByFile(wordFile);
    }
    /**
     * @param fileName:文件名称
     * @param params: 占位符填充, 占位符必须使用${xxx}包裹, params中写成{"xxx":"value"}的形式, 不需要填充传null
     * @param dataArr:添加表的数组格式[["参数1","参数2"],["参数1","参数2"]]
     * @Description:word转word 有表格的追加表格数据
     * @Author: zhongdl
     * @Date:2022/4/25 15:46

     * @return: {@link byte[] }
     **/
    public static File wordToWordBytesAddTable(String fileName, Map<String, String> params,  String[][]...dataArr) throws FileNotFoundException {
        InputStream localStream = SpringUtils.getLocalStream(fileName);
        savePic(localStream,FileUtil.getName(fileName));
        File wordFile = new File("temps/" + FileUtil.getName(fileName));
        Document document = new Document();
        byte[] bytes = wordToWordBytes(wordFile, params);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        document.loadFromStream(byteArrayInputStream,FileFormat.Docx);

        int dataArrLength = dataArr.length;
        for (int z = 0; z < dataArrLength; z++) {
            Section section = document.getSections().get(0);
            Table table = section.getTables().get(z);
            String[][] data = dataArr[z];
            int length = data.length;
            //设置表格的行数和列数
            for (int i = 0; i < length; i++) {
                String[] cellData = data[i];
                 int dataLength = cellData.length;
                TableRow tableRow = table.addRow(dataLength);
                for (int j = 0; j < dataLength; j++) {
                    Paragraph p = tableRow.getCells().get(j).addParagraph();
                    p.appendText(cellData[j]);

                }

            }

        }

        //保存至临时文件目录
        String tempName = "temps" +File.separator+ UUID.randomUUID() + ".docx";

        document.saveToFile(tempName,FileFormat.Docx);


        return new File(tempName);
    }

    /**
     * @param file:文件对象
     * @param data: 表格数据
     * @Description:在word末尾追加数据
     * @Author: zhongdl
     * @Date:2022/5/13 11:14

     * @return: {@link java.io.File }
     **/
    public static File wordToWordBytesAddTable(File file,String[][] data)  {
        Document document = new Document();
        try {
            document.loadFromStream(new FileInputStream(file),FileFormat.Docx);

        Section section = document.getSections().get(0);
        Table table = section.addTable();
        int length = data.length;

        //设置表格的行数和列数
        for (int i = 0; i < length; i++) {
            String[] cellData = data[i];
            if (i == 0){
                table.resetCells(length, cellData.length);
            }
            TableRow tableRow = table.getRows().get(i);
            for (int j = 0; j < tableRow.getCells().getCount(); j++) {
               tableRow.getCells().get(j).addParagraph().appendText(cellData[j]);

            }

        }
            //给表格应用样式
//            table.applyStyle(DefaultTableStyle.Colorful_List);

            //设置表格的右边框
            table.getTableFormat().getBorders().getRight().setBorderType(BorderStyle.Hairline);
//            table.getTableFormat().getBorders().getRight().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getRight().setColor(Color.BLACK);

            //设置表格的顶部边框
            table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Hairline);
//            table.getTableFormat().getBorders().getTop().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getTop().setColor(Color.BLACK);

            //设置表格的左边框
            table.getTableFormat().getBorders().getLeft().setBorderType(BorderStyle.Hairline);
//            table.getTableFormat().getBorders().getLeft().setLineWidth(1.0F);
            table.getTableFormat().getBorders().getLeft().setColor(Color.BLACK);

            //设置表格的底部边框
            table.getTableFormat().getBorders().getBottom().setBorderType(BorderStyle.Hairline);

            //设置表格的水平和垂直边框
            table.getTableFormat().getBorders().getVertical().setBorderType(BorderStyle.Hairline);
            table.getTableFormat().getBorders().getHorizontal().setBorderType(BorderStyle.Hairline);
            table.getTableFormat().getBorders().getVertical().setColor(Color.BLACK);
        //保存至临时文件目录
        String tempName = "temps" +File.separator+ UUID.randomUUID() + ".docx";

        document.saveToFile(tempName,FileFormat.Docx);


        return new File(tempName);
        }  catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * @param bytes:
     * @param data:
     * @param tableIndex: 表格索引
     * @Description:处理不固定的表格表头

     * @return: {@link byte[] }
     **/
    public static byte[] wordToWordBytesAddTable(byte[] bytes,String[][] data,int tableIndex) throws FileNotFoundException {
        Document document = new Document();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        document.loadFromStream(byteArrayInputStream,FileFormat.Docx);
        Section section = document.getSections().get(0);
        Table table = section.getTables().get(tableIndex);
        TableRow firstRow = table.getFirstRow();
        RowCollection rows = table.getRows();
        for (int i = 0; i < data.length; i++) {
            rows.remove(table.getLastRow());
        }

        rows.remove(table.getFirstRow());
        table.removeAbsPosition();

        int length = data.length;

        //设置表格的行数和列数
            for (int i = 0; i < length; i++) {
                String[] cellData = data[i];
                if (i == 0){
                    table.resetCells(length, cellData.length);
                }
                TableRow tableRow = table.getRows().get(i);
                tableRow.setHeight(20);
                for (int j = 0; j < tableRow.getCells().getCount(); j++) {
                    TextRange textRange = tableRow.getCells().get(j).addParagraph().appendText(cellData[j]);
                    textRange.getCharacterFormat().setFontName("Arial");
                    textRange.getCharacterFormat().setFontSize(10f);
                }

            }
        //列宽自动适应内容
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);
        //保存至临时文件目录
        String tempName = "temps" +File.separator+ UUID.randomUUID() + ".docx";

        document.saveToFile(tempName,FileFormat.Docx);


        return wordToWordBytes(new File(tempName),new HashMap<>());
    }


    public static byte[] wordMerge(byte[]... bytes){
        int length = bytes.length;
        if (length == 0){
            return null;
        }
        if (length == 1){
            return bytes[0];
        }
        Document document = new Document();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes[0]);
        document.loadFromStream(byteArrayInputStream,FileFormat.Docx);

        for (int i = 1; i < length; i++) {
            Section lastSection = document.getLastSection();
            Document document2 = new Document();
            document2.loadFromStream(new ByteArrayInputStream(bytes[i]),FileFormat.Docx);
            //将第二个文档的段落作为新的段落添加到第一个文档的最后一个section
            for (Section section:(Iterable <Section>)document2.getSections()) {
                for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
                ) {
                    lastSection.getBody().getChildObjects().add(obj.deepClone());
                }
            }
        }
        //保存至临时文件目录
        String tempName = "temps" +File.separator+ UUID.randomUUID() + ".docx";

        document.saveToFile(tempName,FileFormat.Docx);



        return wordToWordBytes(new File(tempName),new HashMap<>());

    }
    public static File wordMerge(File... files){
        int length = files.length;
        if (length == 0){
            return null;
        }
        if (length == 1){
            return files[0];
        }
        Document document = new Document();
        document.loadFromFile(files[0].getAbsolutePath(),FileFormat.Docx);

        for (int i = 1; i < length; i++) {
            Section lastSection = document.getLastSection();
            Document document2 = new Document();
            document2.loadFromFile(files[i].getAbsolutePath(),FileFormat.Docx);
            //将第二个文档的段落作为新的段落添加到第一个文档的最后一个section
            for (Section section:(Iterable <Section>)document2.getSections()) {
                for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
                ) {
                    lastSection.getBody().getChildObjects().add(obj.deepClone());
                }
            }
        }
        //保存至临时文件目录
        String tempName = "temps" +File.separator+ UUID.randomUUID() + ".docx";

        document.saveToFile(tempName,FileFormat.Docx);



        return removeSpireDocWater(new File(tempName));

    }
    private static void savePic(InputStream inputStream, String fileName) {
        OutputStream os = null;
        try {
            String path = "temps/";
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
